package com.ibm.epss.android;

/**
 * Created with IntelliJ IDEA.
 * User: faramir
 * Date: 11/29/13
 * Time: 10:29 AM
 * To change this template use File | Settings | File Templates.
 */
import java.io.IOException;
import java.net.Authenticator;
import java.net.HttpURLConnection;
import java.net.PasswordAuthentication;
import java.net.URL;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import  org.json.JSONObject;

public class OrderTrackingRestClient {

    public static void postJSONObject(String url, String user, String password,
                                      JSONObject obj) throws Exception {
        prepareSecurity(user, password);
        HttpURLConnection huc = (HttpURLConnection) new URL(url)
                .openConnection();
        prepareHeader(huc);

        huc.addRequestProperty("Content-Type", "application/json");
        huc.setRequestMethod("POST");

        huc.setDoOutput(true);
        huc.getOutputStream().write(obj.toString().getBytes());
        huc.getOutputStream().flush();

        int respCode = huc.getResponseCode();
        System.out.println("PUT " + url + " with response " + respCode);
        huc.disconnect();
    }

    private static void prepareHeader(HttpURLConnection huc) throws Exception {
        huc.addRequestProperty("X-IBM-Workload-Deployer-API-Version", "3.1");
        huc.addRequestProperty("Accept", "application/json");
    }

    private static void prepareSecurity(final String user, final String password)
            throws Exception {
        // Set authenticator
        Authenticator.setDefault(new Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(user, password.toCharArray());
            }
        });

        // Accept all the SSL cert
        SSLContext context = getSSLContext();
        HostnameVerifier hv = new HostnameVerifier() {
            public boolean verify(String hostname, SSLSession session) {
                // Accept all the host
                return true;
            }
        };
        HttpsURLConnection.setDefaultSSLSocketFactory(context
                .getSocketFactory());
        HttpsURLConnection.setDefaultHostnameVerifier(hv);
    }

    private static class AcceptAllTrustManager implements X509TrustManager {
        public void checkClientTrusted(X509Certificate[] arg0, String arg1)
                throws CertificateException {
            // Does nothing, accepts all
        }

        public void checkServerTrusted(X509Certificate[] arg0, String arg1)
                throws CertificateException {
            // Does nothing, accepts all
        }

        public X509Certificate[] getAcceptedIssuers() {
            return null;
        }
    }

    private static SSLContext getSSLContext() throws NoSuchAlgorithmException,
            KeyManagementException {
        // Get the SSL context
        SSLContext context = null;
        context = SSLContext.getInstance("SSL");
        TrustManager[] tms = new TrustManager[1];
        tms[0] = new AcceptAllTrustManager();

        // Use default random number generator (param3)
        context.init(null, tms, null);
        return context;
    }

    // public static void main(String[] args) throws Exception {
    // String protocal = "http";
    // String host = "localhost";
    // String port = "8080";
    // String context = "se";
    // String patternRoot = "rest";
    // String user = "scott";
    // String password = "";
    // ReaderClient reader = new ReaderClient(protocal, host, port, context,
    // patternRoot, user, password);
    // JSONObject tags = reader.readTags();
    //
    // System.out.println("========tags======");
    // System.out.println(tags.toString());
    // }

}
